﻿using JzSport.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JzSport.Api
{
    class RegisterByPhoneAction : PostAction<Params.RegisterPyPhoneParams, Results.RegisterByPhoneResult>
    {
        protected override ActionResult<Results.RegisterByPhoneResult> OnExecute(ActionContext context, SysParameters sysParameters,
            Params.RegisterPyPhoneParams opParams)
        {
            AccountService service = new AccountService();
            ServiceResult<Account> serviceResult = service.RegisterByPhone(
                opParams.Phone,
                opParams.NickName,
                opParams.Password,
                opParams.Verifycode);

            Results.RegisterByPhoneResult actionResult = new Results.RegisterByPhoneResult();

            if (serviceResult.ErrorCode == ErrorCode.NoError)
            {
                actionResult.Id = serviceResult.Data.Id;
                actionResult.Name = serviceResult.Data.Name;
                actionResult.Phone = serviceResult.Data.Phone;

                // 注册成功之后，登录
                ServiceResult<LoginResult> loginServiceResult = service.LoginByPhone(opParams.Phone, opParams.Password);

                if (loginServiceResult.ErrorCode == ErrorCode.NoError)
                {
                    actionResult.Token = Models.UIDToken.ToToken(Models.u.build(serviceResult.Data.Id, DateTime.Now.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss")));
                    actionResult.Sex = loginServiceResult.Data.Sex;
                    actionResult.AvatarUrl = string.Format("{0}{1}", Configs.BaseWebUrl, loginServiceResult.Data.AvatarUrl);
                    actionResult.NickName = loginServiceResult.Data.NickName;
                    actionResult.City = loginServiceResult.Data.City;
                    return new ActionResult<Results.RegisterByPhoneResult>("1.0.2",
                        true, serviceResult.ErrorCode,
                        ErrorCode.ToString(serviceResult.ErrorCode), actionResult);
                }
            }
            return new ActionResult<Results.RegisterByPhoneResult>("1.0.2",
                false, serviceResult.ErrorCode,
                    ErrorCode.ToString(serviceResult.ErrorCode), actionResult);
        }
    }
}
